const express = require('express');
const bodyParser = require('body-parser');
const db = require('node-little-db');
const path = require('path');
const {exec} = require("child_process");

const app = express();

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

const dataBase = db.create('data');

// 得到已报名有效人数
function getValidLength() {
    let sum = 0;
    dataBase.stds.forEach((e) => {
        if (e.status == 1) {
            sum++;
        }
    });
    return sum;
}

// 得到活跃度最低的人的索引
function getMinActivityIndex() {
    let min,
        index = 0;
    for (let i = 0; i < dataBase.stds.length; i++) {
        if (dataBase.stds[i].status == 0) {
            continue;
        }
        if (i == 0) {
            min = dataBase.stds[i].lastOnline * dataBase.stds[i].activity;
        }
        if (dataBase.stds[i].lastOnline * dataBase.stds[i].activity < min) {
            index = i;
            min = dataBase.stds[i].lastOnline * dataBase.stds[i].activity;
        }
    }
    return index;
}

// 报名注册
app.post('/api/regist', (req, res) => {
    let data = req.body;
    data.id = +data.id;

    let index = dataBase.stds.findIndex((v, i) => {
        return data.id == v.id;
    });

    if (index == -1) {
        let obj = {
            id: data.id,
            name: data.name,
            activity: 1,
            lastOnline: Date.now(),
            comment: '',
            status: 1,
        };

        if (getValidLength() >= dataBase.amount) {
            // 已经招满了，把活跃度最低的人踢了
            let i = getMinActivityIndex();
            dataBase.stds[i].status = 0;
            dataBase.stds[i].comment = '因活跃度低被替代';
        }
        dataBase.stds.push(obj);
        res.json({
            success: true,
            msg: `${data.name}同学报名成功！学号为${data.id},当前活跃度为 1，记得每天来打卡哦！`,
        });
    } else {
        let msg = '';
        if (dataBase.stds[index].name != data.name) {
            msg += `修改姓名成功！将名称从 ${dataBase.stds[index].name} 改为 ${data.name}\n`;
        }

        if (dataBase.stds[index].status == 0) {
            if (getValidLength() >= dataBase.amount) {
                // 已经招满了，把活跃度最低的人踢了
                let i = getMinActivityIndex();
                dataBase.stds[i].status = 0;
                dataBase.stds[i].comment = '因活跃度低被替代';
            }
            dataBase.stds[index].status = 1;
            dataBase.stds[index].activity = 1;
            dataBase.stds[index].lastOnline = Date.now();
            msg += `欢迎回来！,当前活跃度为 ${dataBase.stds[index].activity}，记得每天来打卡哦！`;
        } else {
            dataBase.stds[index].activity++;
            dataBase.stds[index].lastOnline = Date.now();
            msg += `打卡成功！,当前活跃度为 ${dataBase.stds[index].activity}，记得每天来打卡哦！`;
        }

        res.json({
            success: true,
            msg,
        });
    }
});

// 查询
app.get('/api/query/:id', (req, res) => {
    let id = req.params.id;
    if (id == 'all') {
        res.json({
            success: true,
            data: dataBase.stds,
        });
    } else {
        id = +id;
        let index = dataBase.stds.findIndex((v, i) => {
            return id == v.id;
        });

        if (index == -1) {
            res.json({
                success: false,
                msg: '未找到！',
                data: [],
            });
        } else {
            res.json({
                success: true,
                data: [dataBase.stds[index]],
            });
        }
    }
});

// 剔除
app.delete('/api/:id', (req, res) => {
    let id = +req.params.id;
    dataBase.stds.forEach((v, i) => {
        if (v.id == id) {
            v.status = 0;
            v.comment = '被管理员剔除';
            res.json({
                success: true,
                msg: '剔除成功',
            });
            return true;
        }
    });
});

// 得到招收总人数
app.get('/api/amount', (req, res) => {
    res.json(dataBase.amount);
});

// 修改招收总人数
app.get('/api/modifyamount/:amount', (req, res) => {
    let newAmount = +req.params.amount;
    dataBase.amount = newAmount;
    res.json({
        success: true,
        msg: '修改招收人数成功！',
    });
});

app.listen(3000);
console.log('http://localhost:3000');
exec(`start http://localhost:3000`);
